<?php
namespace AuctionCore\Dispute;

use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\Dispute\PurchaseOrder;
use AuctionCore\CarResource\CarModel;
use AuctionCore\CarResource\Car;
use AuctionCore\System\AuctionException;


class DisputeOrder
{
    const STATUS_HANDLE = 0; // 待审核
    const STATUS_ADOPT = 1; // 已通过
    const STATUS_REJECT = 2; // 驳回

    const CUSTOMER_DEALER = 1; //车商
    const CUSTOMER_OWNER = 2; //车主

    protected $did = null;

    //添加争议
    public function DisputeAdd($data){
        //事务开始
        M()->startTrans();
        $res_dispute = M('dispute')->add($data);
        $map['order_id'] = array('eq',$data['order_id']);
        $info['dealer_issue_status'] = 1;
        $info['is_dealer_issue'] = 1;
        $res_order = M('order')->where($map)->save($info); //更改order表中success_dealer_id = dealer_id 的dealer_issue_status = 1;
        //锁定拍单 采购单 收付款单
        $res_lock = self::lockAll($data);

        if ($data['od_type'] == self::CUSTOMER_DEALER)
            $customer = "dealer_id";
        elseif ($data['od_type'] == self::CUSTOMER_OWNER)
            $customer = "owner_id";
        if ($res_dispute && $res_lock && $res_order) {
            //事务提交
            M()->commit();
            //记录操作日志
            $log = array('order_id' => $data['order_id'], $customer => $data['od_id'], 'action' => '产生争议');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            \Think\Log::record('添加争议时发生回滚事件！order_id:' . $data['order_id'] . ',' . $customer . ':' . $data['od_id']);
            AuctionException::make_throw('100066');
        }
    }
    public function get_modify_list($dealer_id,$page,$pagesize){
        $map['o.success_dealer_id'] = $dealer_id;
       /* $map['o.dealer_issue_status'] = array('in','3,4');
        $map['ml.modify_result'] = array('eq',2);*/
        //$map['_string']  = "o.dealer_issue_status in(2,3,4) OR ml.modify_result = 2";
        $map['ml.status'] = array('neq','4');
        $map['ml.modify_result'] = array('eq',2);
        $cols = 'ml.mid,ml.did,ml.modify_reason,ml.modify_result,ml.modify_desc,ml.status,ml.createtime,ml.dealtime,ml.completetime,ml.refusetime,
        ml.canceltime,ml.dealer_compensate,ml.dealer_deduction,o.order_no,o.order_id,c.car_id,c.transfer_limit,c.series_id,c.brand_id,c.car_cc,c.turbo,c.gearbox,
        o.order_no,c.location_area,o.bidding_end_time';
        $list = M("order")->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join('inner join '.C('DB_PREFIX') . "modify_list as ml ON ml.`order_id` = o.`order_id`")
            ->where($map)->order('ml.createtime desc')->limit($pagesize)->page($page)->select();
        $total = M("modify_list")->alias('ml')
            ->join(C('DB_PREFIX') . "order as o ON ml.`order_id` = o.`order_id`")
            ->where($map)->count();
        if (!empty($list)) {
            //车辆基本信息
            $cm = new CarModel();
            $a = new \AuctionCore\Other\Address();
            foreach ($list as $key => $val) {
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $city_name = $a->get_name_by_code($val['location_area']);
                $list[$key]['model'] = '[' . $city_name . '] ' . $series['name'] . ' ' . $val['car_cc'] . ($val['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $val['gearbox']);
            }
        }
        return $result =  array(
            'list'=>$list,
            'total'=>$total
        );
    }
    //获取异常车辆详情
    public function get_modify_detail($order_id,$dealer_id){
        $map['o.success_dealer_id'] = array('eq',$dealer_id);
        $map['o.order_id'] = array('eq',$order_id);
        $map['ml.status'] = array('neq',4);
        $map['ml.modify_result'] = array('eq',2);
        $cols = 'ml.mid,ml.did,ml.modify_reason,ml.modify_result,ml.modify_desc,ml.status,ml.createtime,ml.dealtime,ml.completetime,ml.refusetime,
        ml.canceltime,ml.dealer_compensate,ml.dealer_deduction,o.order_no,o.order_id,c.car_id,c.transfer_limit,c.series_id,c.brand_id,c.car_cc,c.turbo,c.gearbox,
        o.order_no,c.location_area,o.bidding_end_time';
        $list = M("order")->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON o.car_id = c.car_id")
            ->join(C('DB_PREFIX') . "modify_list as ml ON ml.order_id = o.order_id")
            ->where($map)->find();
        return $list;
    }
    public function get_dispute_list($dealer_id,$page,$pagesize){
        $map['o.success_dealer_id'] = $dealer_id;
        $map['d.od_type'] = array('eq',1); //必须是车商
        //$map['o.dealer_issue_status'] = array('eq',1); //dealer_issue_status状态为1时,则说明该车处于争议状态 --兼容老数据
        $cols = 'd.did,d.remark,d.dispute_reason,d.status,d.auditing_result,d.reject_result,d.createtime,d.audittime,d.order_status,o.order_no,o.order_id,c.car_id,c.transfer_limit,c.series_id,c.brand_id,c.car_cc,c.turbo,c.gearbox,o.order_no,c.location_area,o.bidding_end_time';
        $list = M("order")->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join("inner join ".C('DB_PREFIX') . "dispute as d ON d.`order_id` = o.`order_id`")
            ->where($map)->order('d.createtime desc')->limit($pagesize)->page($page)->select();
        $total = M("order")->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join("inner join ".C('DB_PREFIX') . "dispute as d ON d.`order_id` = o.`order_id`")
            ->where($map)->count();
        if (!empty($list)) {
            $cm = new CarModel();
            $a = new \AuctionCore\Other\Address();
            foreach ($list as $key => $val) {
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $city_name = $a->get_name_by_code($val['location_area']);
                $list[$key]['model'] = '[' . $city_name . '] ' . $series['name'] . ' ' . $val['car_cc'] . ($val['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $val['gearbox']);
            }
        }
        return $result =  array(
            'list'=>$list,
            'total'=>$total
        );
    }
    //获取争议车辆详情
    public function get_dispute_detail($did){
        $map = array();
        $map['d.did'] = array('eq',$did);
        $cols = 'd.did,d.remark,d.dispute_reason,d.status,d.auditing_result,d.reject_result,d.createtime,d.audittime,d.order_status,o.order_no,o.order_id,c.car_id,c.transfer_limit,c.series_id,c.brand_id,c.car_cc,c.turbo,c.gearbox,o.order_no,c.location_area,o.bidding_end_time';
        $list = M("dispute")->alias('d')->field($cols)
            ->join("inner join ".C('DB_PREFIX') . "order as o ON d.`order_id` = o.`order_id`")
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->where($map)->find();
        return $list;
    }
    //通过did查询争议车辆的处理结果
    public function getmodify_resultbydid($did){
        $map['d.did'] = array('eq',$did);
        $info = M('dispute')->alias('d')->field('ml.modify_result,ml.mid,ml.dealer_compensate')
            ->join(C('DB_PREFIX') . "modify_list as ml ON d.`did` = ml.`did`")
            ->where($map)->find();
        return $info;
    }
    private function lockAll($data){
        //拍单锁定
        $o = new AuOrder($data['order_id']);
        $orderInfo = $o->detail();
        $res_order = $o->lockByOrderId();
        ///采购单锁定
        $po = new PurchaseOrder($data['po_id']);
        $res_purchase_order = $po->lockById();

        //付款单锁定(采购单)
        $payment_id = $po->getPaymentIdByPoid();
        $res_payment = true;
        if ($payment_id) {
            $payment_info = $this->getPaymentInfo($payment_id);
            if ($payment_info['status'] == 0) {
                $res_payment = $this->Payment_lock($payment_id);
            }
        }
        //收款锁定(拍单)
        $collection_id = $o->getCollectionIdByOid();
        $res_collection = true;
        if ($collection_id) {
            $collection_info = $this->getCollectionInfo($collection_id);
            if ($collection_info['status'] == 0) {
                $res_collection = $this->Collection_lock($collection_id);
            }
        }
        if ($res_order && $res_purchase_order && $res_payment && $res_collection ) {
            return true;
        }else{
            return false;
        }
    }
    /**
     * 锁定收款单
     * @param $id
     * @return bool
     */
    public static function Payment_lock($id)
    {
        if (intval($id) < 1) return false;
        $data = [
            'status' => 2,
            'update_time' => date('Y-m-d H:i:s'),
        ];
        return M("payment")->where(['id' => $id])->save($data);
    }
    /**
     * 锁定收款单
     * @param $id
     * @return bool
     */
    public function Collection_lock($collection_id){
        if (intval($collection_id) < 1) return false;
        $data = [
            'status' => 2,
            'update_time' => date('Y-m-d H:i:s'),
        ];
        return M("collection")->where(['id' => $collection_id])->save($data);
    }
    /**
     * 获取付款信息
     * @return mixed
     */
    public function getPaymentInfo($payment_id)
    {
        if ($payment_id < 1) return false;
        return M('payment')->where(['id' =>$payment_id])->find();
    }
    /**
     * 获取收款信息
     * @return bool|mixed
     */
    public function getCollectionInfo($collection_id)
    {
        if (intval($collection_id) < 1) return false;
        return M('collection')->where(['id' => $collection_id])->find();
    }
}